<?php

DB::load();

class DB_Model
{
	public static $primaryKey;
	public static $errorOut = false;

	/**
	 * @var QB
	 */
	public static $QB;
	public static $ready = false;

	public static function prepare($database, $table, $primaryKey=false)
	{
		self::$primaryKey = $primaryKey;
		self::$QB = new QB($table,$database);

		if($primaryKey)
		self::$QB->addVar($primaryKey,QB::EQUALS);

		self::$ready = false;
	}

	public static function mergeInputs($old, $new)
	{
		foreach( $new as $key=> $val)
		{
			if($val!==false)
			$old[$key]=$val;
		}

		return $old;
	}

	public static function get($input)
	{
		/**
		 * Setup QB With Some Input
		 */
		if(is_array($input))
		self::$QB->source = $input;
		else
		self::$QB->source = array(self::$primaryKey=>$input);

//		print_r(self::$QB);

		/**
		 * Check Validity
		 */
		if(!$result = DB::query(self::$QB->db, self::$QB->query())->fetch_all())
		{
			if(self::$errorOut)
			{
				Error::show("No Such Entry","No Entry Exists With This ID");
				/**
				 * @todo Add Error Log
				 */
			}
			else
			return array();
		}

		/**
		 * Results In A Multi-Dimensional Array()
		 */
		return $result;
	}

	public static function timestamp(&$timestamp)
	{
		if(!is_int($timestamp))
		return false;

		$timestamp = date("Y-m-d H:i:s",$timestamp);
		return true;
	}

	public static function checkNull(&$var)
	{
		$var = (int) $var;

		if(!is_int($var))
		return false;

		$var = $var ? $var : null;
		return true;
	}
}